<template>
  <el-input v-model="comVal" :disabled="disabled" />
</template>

<script>
export default {
  name: "CodeGenerate",
  // model: {
  //   prop: "value",
  //   event: "changeValue",
  // },
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    prefix: {
      type: String,
      default: "",
    },
    codeLength: {
      type: Number,
      default: 32,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      comVal: "",
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        if (newVal) {
          this.comVal = newVal;
        } else {
          this.comVal = this.generateCode();
        }
      },
      immediate: true,
    },
    comVal: {
      handler(newVal) {
        this.$emit("update:modelValue", newVal);
      },
      immediate: true,
    },
  },
  methods: {
    generateCode() {
      let str = "";
      for (let i = 0; i < this.codeLength; i++) {
        str += "x";
      }
      return this.prefix + this.guuid(str);
    },
    guuid(str) {
      return str.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
  },
};
</script>
